package com.example.myapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.cardview.widget.CardView;

import com.example.myapplication.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class ProfileEditActivity extends AppCompatActivity {
    private static final String PREF_PROFILE = "profile_info";
    private static final String KEY_AGE = "user_age";
    private static final String KEY_RESIDENCE = "user_residence";
    private static final String KEY_INTEREST = "user_interest";
    private static final int REQUEST_INTEREST = 11;
    private static final int REQUEST_PERMISSION_STORAGE = 102;
    private static final int REQUEST_PICK_IMAGE = 103;
    private static final String AVATAR_DIR_NAME = "avatars";
    private static final String AVATAR_FILE_PREFIX = "avatar_";
    private static final String TAG = "ProfileEditDebug";

    private UserViewModel userViewModel;
    private SharedPreferences sharedPreferences;
    private TextView tvUsernameContent;
    private Spinner spinnerAge;
    private EditText etResidence;
    private TextView tvInterestContent;
    private Button btnBack, btnSave, btnReset;
    private CardView avatarCard;
    private ImageView ivAvatar;
    private String userId;
    private File avatarStorageDir;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_edit);

        sharedPreferences = getSharedPreferences(PREF_PROFILE, MODE_PRIVATE);
        try {
            userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
            Log.d(TAG, "ViewModel初始化成功");
        } catch (Exception e) {
            Log.e(TAG, "ViewModel初始化失败：" + e.getMessage());
            Toast.makeText(this, "初始化失败，请重试", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        String usernameFromHome = getIntent().getStringExtra("username");
        userId = getIntent().getStringExtra("userId");
        if (userId == null) {
            userId = usernameFromHome != null ? usernameFromHome : "default_user_001";
            Log.d(TAG, "使用默认userId：" + userId);
        }

        try {
            initAvatarStorageDir();
        } catch (Exception e) {
            Log.e(TAG, "头像目录初始化失败：" + e.getMessage());
            Toast.makeText(this, "头像功能暂时不可用", Toast.LENGTH_SHORT).show();
        }

        try {
            initViews();
            initPageData();
            setupAllListeners();
        } catch (Exception e) {
            Log.e(TAG, "页面初始化失败：" + e.getMessage());
            Toast.makeText(this, "页面加载失败，请重试", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        if (usernameFromHome != null) {
            userViewModel.updateUsername(usernameFromHome);
            Log.d(TAG, "同步用户名：" + usernameFromHome);
        }
    }

    private void initViews() {
        tvUsernameContent = findViewById(R.id.tv_username_content);
        spinnerAge = findViewById(R.id.spinner_age);
        etResidence = findViewById(R.id.et_residence);
        tvInterestContent = findViewById(R.id.tv_interest_content);
        btnBack = findViewById(R.id.btn_back);
        btnSave = findViewById(R.id.btn_save);
        btnReset = findViewById(R.id.btn_reset);
        avatarCard = findViewById(R.id.avatar_card);
        ivAvatar = findViewById(R.id.iv_avatar);

        if (tvUsernameContent == null || spinnerAge == null || etResidence == null ||
                tvInterestContent == null || btnBack == null || btnSave == null ||
                btnReset == null || avatarCard == null || ivAvatar == null) {
            Log.e(TAG, "部分控件绑定失败！请检查布局ID是否正确");
            throw new RuntimeException("控件绑定失败，可能是布局ID不匹配");
        }
    }

    private void initPageData() {
        userViewModel.getUsername().observe(this, username -> {
            String showName = username != null ? username : "未登录";
            tvUsernameContent.setText(showName);
            Log.d(TAG, "更新用户名显示：" + showName);
        });

        initAgeSpinner();
        loadSavedProfile();

        try {
            loadUserAvatar();
        } catch (Exception e) {
            Log.e(TAG, "加载头像失败：" + e.getMessage());
            ivAvatar.setImageResource(R.drawable.touxiang);
        }
    }

    private void initAvatarStorageDir() {
        avatarStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), AVATAR_DIR_NAME);
        if (!avatarStorageDir.exists()) {
            boolean isCreated = avatarStorageDir.mkdirs();
            if (!isCreated) {
                Log.e(TAG, "头像目录创建失败");
                throw new RuntimeException("头像目录创建失败，无法保存头像");
            }
        }
    }

    private void initAgeSpinner() {
        List<String> ageList = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            ageList.add(i + "岁");
        }

        android.widget.ArrayAdapter<String> adapter = new android.widget.ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                ageList
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerAge.setAdapter(adapter);
        spinnerAge.setSelection(17);
    }

    private void loadSavedProfile() {
        String savedResidence = sharedPreferences.getString(KEY_RESIDENCE, "");
        etResidence.setText(savedResidence);

        userViewModel.getCurrentInterest().observe(this, interest -> {
            String showInterest = (interest != null && !"未选择兴趣".equals(interest))
                    ? interest
                    : sharedPreferences.getString(KEY_INTEREST, "点击可以让更多人认识你^^");
            tvInterestContent.setText(showInterest);
        });

        int savedAge = sharedPreferences.getInt(KEY_AGE, 18);
        if (savedAge >= 1 && savedAge <= 100) {
            spinnerAge.setSelection(savedAge - 1);
        } else {
            spinnerAge.setSelection(17);
        }
    }

    private void setupAllListeners() {
        btnBack.setOnClickListener(v -> finish());

        btnSave.setOnClickListener(v -> {
            try {
                saveProfileInfo();
            } catch (Exception e) {
                Log.e(TAG, "保存信息失败：" + e.getMessage());
                Toast.makeText(this, "保存失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });

        btnReset.setOnClickListener(v -> resetProfileInfo());

        tvInterestContent.setOnClickListener(v -> {
            try {
                Intent intent = new Intent(ProfileEditActivity.this, InterestSelectionActivity.class);
                startActivityForResult(intent, REQUEST_INTEREST);
            } catch (Exception e) {
                Log.e(TAG, "跳转兴趣页失败：" + e.getMessage());
                Toast.makeText(this, "兴趣选择页未找到，请检查配置", Toast.LENGTH_SHORT).show();
            }
        });

        avatarCard.setOnClickListener(v -> {
            try {
                checkStoragePermissionForAvatar();
            } catch (Exception e) {
                Log.e(TAG, "打开相册失败：" + e.getMessage());
                Toast.makeText(this, "无法打开相册，请重试", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void checkStoragePermissionForAvatar() {
        boolean hasPermission = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            hasPermission = ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED;
        } else {
            hasPermission = ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }

        if (hasPermission) {
            openSystemGallery();
        } else {
            requestAvatarStoragePermission();
        }
    }

    private void requestAvatarStoragePermission() {
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{android.Manifest.permission.READ_MEDIA_IMAGES};
        } else {
            permissions = new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE};
        }
        requestPermissions(permissions, REQUEST_PERMISSION_STORAGE);
    }

    private void openSystemGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        galleryIntent.setType("image/*");
        try {
            startActivityForResult(galleryIntent, REQUEST_PICK_IMAGE);
        } catch (Exception e) {
            Log.e(TAG, "相册应用未找到：" + e.getMessage());
            Toast.makeText(this, "未找到可用相册应用，请安装相册后重试", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveProfileInfo() {
        String ageStr = spinnerAge.getSelectedItem().toString().replace("岁", "");
        int age;
        try {
            age = Integer.parseInt(ageStr);
        } catch (NumberFormatException e) {
            Log.e(TAG, "年龄格式错误：" + ageStr);
            Toast.makeText(this, "年龄格式错误", Toast.LENGTH_SHORT).show();
            return;
        }

        String residence = etResidence.getText().toString().trim();
        String interest = tvInterestContent.getText().toString().trim();

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(KEY_AGE, age);
        editor.putString(KEY_RESIDENCE, residence);
        editor.putString(KEY_INTEREST, interest);
        editor.apply();

        userViewModel.updateInterest(interest);

        Toast.makeText(this, "信息保存成功！", Toast.LENGTH_SHORT).show();
    }

    private void resetProfileInfo() {
        etResidence.setText("");
        tvInterestContent.setText("点击可以让更多人认识你^^");
        spinnerAge.setSelection(17);
        Toast.makeText(this, "信息已重置！", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_INTEREST && resultCode == RESULT_OK && data != null) {
            String selectedInterest = data.getStringExtra("selected_interest");
            if (selectedInterest != null) {
                tvInterestContent.setText(selectedInterest);
                userViewModel.updateInterest(selectedInterest);
            }
        } else if (requestCode == REQUEST_PICK_IMAGE && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                boolean isSaveSuccess = saveSelectedAvatarToPrivateDir(selectedImageUri);
                if (isSaveSuccess) {
                    loadUserAvatar();
                    Toast.makeText(this, "头像更换成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "头像保存失败，请选择其他图片重试", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "未选择有效图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean saveSelectedAvatarToPrivateDir(Uri imageUri) {
        deleteOldUserAvatar();
        File newAvatarFile = new File(avatarStorageDir, AVATAR_FILE_PREFIX + userId + ".png");
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = getContentResolver().openInputStream(imageUri);
            if (inputStream == null) {
                Log.e(TAG, "图片输入流为空");
                return false;
            }

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;
            Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, options);
            if (selectedBitmap == null) {
                Log.e(TAG, "图片解码失败");
                return false;
            }

            outputStream = new FileOutputStream(newAvatarFile);
            return selectedBitmap.compress(Bitmap.CompressFormat.PNG, 80, outputStream);

        } catch (Exception e) {
            Log.e(TAG, "保存头像失败：" + e.getMessage());
            return false;
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
            } catch (Exception e) {
                Log.e(TAG, "流关闭失败：" + e.getMessage());
            }
        }
    }

    private void deleteOldUserAvatar() {
        File oldAvatarFile = new File(avatarStorageDir, AVATAR_FILE_PREFIX + userId + ".png");
        if (oldAvatarFile.exists() && oldAvatarFile.delete()) {
            Log.d(TAG, "旧头像删除成功");
        }
    }

    private void loadUserAvatar() {
        File userAvatarFile = new File(avatarStorageDir, AVATAR_FILE_PREFIX + userId + ".png");
        if (userAvatarFile.exists()) {
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                Bitmap avatarBitmap = BitmapFactory.decodeFile(userAvatarFile.getAbsolutePath(), options);
                if (avatarBitmap != null) {
                    ivAvatar.setImageBitmap(avatarBitmap);
                } else {
                    Log.e(TAG, "头像解码失败，使用默认头像");
                    ivAvatar.setImageResource(R.drawable.touxiang);
                    userAvatarFile.delete();
                }
            } catch (Exception e) {
                Log.e(TAG, "加载本地头像失败：" + e.getMessage());
                ivAvatar.setImageResource(R.drawable.touxiang);
            }
        } else {
            ivAvatar.setImageResource(R.drawable.touxiang);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_STORAGE) {
            boolean isPermissionGranted = false;
            for (int result : grantResults) {
                if (result == PackageManager.PERMISSION_GRANTED) {
                    isPermissionGranted = true;
                    break;
                }
            }

            if (isPermissionGranted) {
                openSystemGallery();
            } else {
                Toast.makeText(this, "需要存储权限才能选择头像，请在【设置-应用-权限】中开启", Toast.LENGTH_LONG).show();
            }
        }
    }
}